package com.tg.app.activity.base;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.text.HtmlCompat;
import androidx.core.util.Consumer;

import com.alibaba.fastjson.JSON;
import com.appbase.custom.base.DeviceFeatureSettings;
import com.appbase.custom.base.ServiceBought;
import com.appbase.custom.constant.CommonConstants;
import com.appbase.custom.constant.DeviceStateConstants;
import com.base.BaseActivity;
import com.tange.base.toolkit.PreferenceUtil;
import com.tange.base.toolkit.TGThreadPool;
import com.tange.core.device.facade.ConnectStatus;
import com.tange.core.device.facade.DeviceFacade;
import com.tange.core.device.facade.Instruction;
import com.tange.core.media.render.DeviceMediaRender;
import com.tange.core.media.source.impl.DeviceMediaSource;
import com.tange.core.media.source.impl.live.DeviceLiveMediaSource;
import com.tange.module.camera.hub.CameraHub;
import com.tange.module.core.wifi.scan.ApScanConfiguration;
import com.tange.module.device.feature.DeviceFeature;
import com.tange.module.device.feature.DeviceFeatureObjectBox;
import com.tange.module.device.feature.DeviceFeature_;
import com.tange.xbanner.XBanner;
import com.tg.app.R;
import com.tg.app.activity.CloudServiceActivity;
import com.tg.app.activity.device.CameraPipPlaybackActivity;
import com.tg.app.activity.device.PlaybackActivity;
import com.tg.app.camera.AVIOCTRLDEFs;
import com.tg.app.camera.Camera;
import com.tg.app.camera.CameraCMDHelper;
import com.tg.app.helper.ActivityHelper;
import com.tg.app.helper.DeviceFeatureHelper;
import com.tg.app.helper.DeviceFunHelper;
import com.tg.app.helper.DeviceHelper;
import com.tg.app.helper.DeviceUIHelper;
import com.tg.app.helper.ServiceInfoHelper;
import com.tg.app.util.ObjectBoxUtil;
import com.tg.app.view.ACCameraPlayerView;
import com.tg.app.view.CameraPlayerSingleView;
import com.tg.app.widget.BottomSheetListDialog;
import com.tg.app.widget.PrePositionDialog;
import com.tg.app.widget.PtzControlView;
import com.tg.app.widget.ZoomView;
import com.tg.appcommon.android.TGApplicationBase;
import com.tg.appcommon.android.TGLog;
import com.tg.appcommon.android.TGToast;
import com.tg.data.bean.DeviceItem;
import com.tg.data.bean.DeviceSettingsInfo;
import com.tg.data.bean.DeviceSettingsInfo_;
import com.tg.data.helper.DeviceTypeHelper;
import com.tg.data.http.entity.DeviceServiceStatusBean;

import java.io.File;
import java.util.HashMap;

import io.objectbox.Box;

public class CameraBaseActivity extends BaseActivity  {
    protected boolean rendered = false;
    protected TextView connectView;
    protected View loadingView;
    public final static int PLAYER_ID_MAIN = 0;
    public final static int PLAYER_ID_MINI = 1;
    public static final String FROM = "start_activity_from";
    public static final String TAG = "CameraBaseActivity";
    protected DeviceFeature mDeviceFeature;
    protected Camera mCamera;
    protected DeviceFacade deviceFacade;
    protected DeviceItem mDevice;
    protected DeviceSettingsInfo deviceSettingsInfo;
    protected DeviceUIHelper mDeviceUIHelper = new DeviceUIHelper();
    protected String mFrom;
    protected int mOrigin;
    protected BottomSheetListDialog bottomSheetListDialog;
    protected PrePositionDialog prePositionHelper;
    protected CameraCMDHelper cmdHelper;
    protected DeviceMediaSource deviceMediaSource;
    protected DeviceMediaRender deviceMediaRender;
    protected final DeviceFunHelper deviceFunHelper = new DeviceFunHelper();
    protected boolean isLandscape = false;
    protected XBanner xBanner;
    protected int currentPlayer = PLAYER_ID_MAIN;
    protected PtzControlView ptzControlView;
    protected final String albumPath = Environment.getExternalStorageDirectory().toString() + File.separator + Environment.DIRECTORY_DCIM;
    public static final int EVENT_SEND_PTZCMD_LONG = 0x02;
    public static final int EVENT_SEND_FOCUSCMD_LONG = 0x0E;
    protected boolean audioEnabled = false;
    protected Button buyButton;
    protected boolean isSaving;
    public void createDeviceMediaRender() {
        deviceMediaSource = new DeviceLiveMediaSource(deviceFacade);
        deviceMediaRender = new DeviceMediaRender(this, deviceMediaSource);
    }

    public boolean isLocalConnect() {
        return CameraHub.getInstance().isEnableLocalApConnect() || mOrigin == DeviceListBaseActivity.OPEN_DRIVE_LOCAL||mOrigin ==DeviceListBaseActivity.OPEN_DRIVE_LOCAL_PALYBACK_SDCARD;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initData(savedInstanceState);
        getDeviceSettings();
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }

    private void registerICameraListener(){
        if (deviceFacade != null) {
            deviceFacade.observeConnectStatus(connectStatusConsumer);
            deviceFacade.getInstruct().observeOnReceive(instructionConsumer);

        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        audioEnabled = deviceMediaSource.isAudioProduceEnabled();
    }

    protected void jumpSettings() {
        if (deviceFacade != null) {
            unregisterICameraListener();
            ActivityHelper.jump2SettingActivityForResult(this, mDevice, mOrigin);
        }
    }

    public void unregisterICameraListener(){
        if (deviceFacade != null) {
            deviceFacade.unObserveConnectStatus(connectStatusConsumer);
            deviceFacade.getInstruct().unObserveOnReceive(instructionConsumer);
        }
    }

    private void initData(@Nullable Bundle savedInstanceState) {
        if (savedInstanceState == null) {
            mOrigin = getIntent().getIntExtra(CommonConstants.EXT_PUSH_ORIGIN, DeviceListBaseActivity.PUSH_TARGET_LIVE);
        }
        mDevice = getIntent().getParcelableExtra(CommonConstants.EXT_DEVICE_ITEM);
        TGApplicationBase.getInstance().putGlobalObject(CameraPlayerSingleView.CUR_DEVICE_UUID, mDevice.uuid);

        deviceFacade = new DeviceFacade(mDevice.uuid);
        registerICameraListener();

        createDeviceMediaRender();


        cmdHelper = new CameraCMDHelper(mCamera);
        mFrom = getIntent().getStringExtra(FROM);
        TGLog.i(TAG, "from = " + mFrom);
        if (mDevice != null) { // 尚云 p2p
            Box<DeviceFeature> box = DeviceFeatureObjectBox.getDeviceFeature();
            if (box != null){
                mDeviceFeature = box.query().equal(DeviceFeature_.uuid, mDevice.uuid).build().findFirst();
                if (mDeviceFeature != null){
                    currentPlayer = mDeviceFeature.currentPlayer;
                    TGApplicationBase.getInstance().putGlobalObject(CameraPlayerSingleView.CUR_DEVICE_FEATURE, mDeviceFeature);
                }
            }
        }
    }

    @Override
    protected void initView() {
        buyButton = findViewById(R.id.btn_playback_view_buy);
        if (buyButton != null) {
            buyButton.setOnClickListener(v -> ActivityHelper.openWebService(CameraBaseActivity.this, mDevice, CloudServiceActivity.EXT_CLOUD_SERVICE_TYPE_SIM));
        }
    }

    public void getGetEnv() {
    }

    public void reportFirstFramePrepare() {}
    public void reportFirstFrameP2P() {}
    public void startLive() {}
    public void connect() {}
    public void setLiveClicked(boolean b) {}
    public boolean isMicrophoneClose() {
        return false;
    }
    public int getLayoutResID() {
        if (DeviceHelper.isLamp(mDevice)){
            return R.layout.lamp_view_activity;
        }
       return R.layout.camera_view_activity;
    }

    public Camera getCamera() {
        return mCamera;
    }

    public String getFrom(){
        return mFrom;
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerICameraListener();
        getDeviceSettings();
        getServiceInfo();
    }

    public void getDeviceSettings() {
        if (mDevice != null) {
            Box<DeviceSettingsInfo> settingsInfoBox = ObjectBoxUtil.getDeviceSettingsInfo();
            if (settingsInfoBox != null) {
                deviceSettingsInfo = settingsInfoBox.query().equal(DeviceSettingsInfo_.uuid, mDevice.uuid).build().findFirst();
            }
            if (deviceSettingsInfo == null) {
                deviceSettingsInfo = new DeviceSettingsInfo();
                deviceSettingsInfo.deviceID = mDevice.id;
                deviceSettingsInfo.uuid = mDevice.uuid;
                deviceSettingsInfo.online = (mDevice.is_online == DeviceStateConstants.DEVICE_ONLINE);
                deviceSettingsInfo.current_version_code = mDevice.current_version_code;
                deviceSettingsInfo.firmware_id = mDevice.firmware_id;
                deviceSettingsInfo.timezone = mDevice.timezone;
                deviceSettingsInfo.quality = AVIOCTRLDEFs.AVIOCTRL_QUALITY_MIN;
                deviceSettingsInfo.quality2 = AVIOCTRLDEFs.AVIOCTRL_QUALITY_MIN;
            }
            TGLog.d("DeviceSettingsActivity", "mDevice.is_open = " + mDevice.is_open);
            deviceSettingsInfo.deviceStatus = mDevice.is_open;
        }
    }


    public void receiveIOCtrlData(int type, byte[] data) {

        try {
            if (type == AVIOCTRLDEFs.IOTYPE_USEREX_IPCAM_GET_FEATURE_RESP) {
                DeviceFeatureSettings.DeviceFeatureSettingsResp settingsResp = JSON.parseObject(data, DeviceFeatureSettings.DeviceFeatureSettingsResp.class);
                TGLog.i(TAG, "[receiveIOCtrlData] IOTYPE_USEREX_IPCAM_GET_FEATURE_RESP , feature =  " + JSON.toJSONString(settingsResp));
                DeviceFeature feature = DeviceFeature.newDeviceFeature(settingsResp);
                if (feature != null) {
                    feature.uuid = mDevice.uuid;
                    if (mDeviceFeature != null) {
                        feature.id = mDeviceFeature.id;
                        feature.currentPlayer = mDeviceFeature.currentPlayer;
                        feature.zoomPos = mDeviceFeature.zoomPos;
                    }
                    final boolean isMultiChannelsUpdated =  DeviceFeatureHelper.hasMultiChannelsUpdate(mDeviceFeature, feature);
                    mDeviceFeature = feature;
                    TGThreadPool.executeOnUiThread(() -> updateLayout(isMultiChannelsUpdated));
                }
                Box<DeviceFeature> box = DeviceFeatureObjectBox.getDeviceFeature();
                assert box != null;
                box.put(mDeviceFeature);

                DeviceSettingsInfo info = DeviceSettingsInfo.newDeviceSettingsInfo(settingsResp);
                if (info != null) {
                    deviceSettingsInfo = DeviceSettingsInfo.updateData(deviceSettingsInfo,info,mDevice);
                    if (DeviceFeatureHelper.supportMultiChannels(mDeviceFeature)) {
                        setMultiChannelsStreamCtrl();
                    }
                    if (mDeviceFeature.isDriveRec){
                        mDevice.device_type = DeviceTypeHelper.DEVICE_DRSIM;
                        if (mDeviceFeature.supportDormant){
                            mDevice.device_type = DeviceTypeHelper.DEVICE_LPDRSIM;
                        }
                    }
                    if (deviceSettingsInfo != null){
                        deviceSettingsInfo.supportTemper = mDeviceFeature.supportTemper;
                        deviceSettingsInfo.supportHumidity = mDeviceFeature.supportHumidity;
                    }
                    assert deviceSettingsInfo != null;
                    TGLog.i(TAG, "[receiveIOCtrlData] IOTYPE_USEREX_IPCAM_GET_FEATURE_RESP , deviceStatus = " + deviceSettingsInfo.deviceStatus);
                    putSettingsInfo();
                }
            }
        } catch (Throwable ex) {
            TGLog.e(TAG, "receiveIOCtrlData ERROR = " + ex);
        }
    }

    protected void putSettingsInfo() {
        TGLog.d(ZoomView.TAG, "putSettingsInfo");
        if (deviceSettingsInfo != null){
            deviceSettingsInfo.updated_at = System.currentTimeMillis();
            Box<DeviceSettingsInfo> deviceSettingsInfoBox = ObjectBoxUtil.getDeviceSettingsInfo();
            if (deviceSettingsInfoBox != null) {
                deviceSettingsInfoBox.put(deviceSettingsInfo);
            }
        }

        if (mDeviceFeature != null){
            Box<DeviceFeature> box = DeviceFeatureObjectBox.getDeviceFeature();
            if (box != null) {
                box.put(mDeviceFeature);
            }
        }
    }

    public void showSettingWifiDialog() {
        @SuppressLint("InflateParams") View view = LayoutInflater.from(this).inflate(R.layout.dialog_camera_live_settings, null);
        TextView title = view.findViewById(R.id.deivce_settings_title_mark);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            title.setText(Html.fromHtml(String.format(getResources().getString(R.string.deivce_settings_title_mark), ApScanConfiguration.INSTANCE.apNamePrefix())));
        } else {
            title.setText(HtmlCompat.fromHtml(String.format(getResources().getString(R.string.deivce_settings_title_mark), ApScanConfiguration.INSTANCE.apNamePrefix()), HtmlCompat.FROM_HTML_MODE_LEGACY));
        }
        final Dialog mDialog = new Dialog(this, com.module.appcommon.R.style.alert_dialog);
        mDialog.setContentView(view);
        mDialog.setCanceledOnTouchOutside(false);
        mDialog.show();
        CheckBox checkBox = view.findViewById(R.id.cb_dialog_camera_live_settings_hide);
        checkBox.setOnCheckedChangeListener((buttonView, isChecked) -> PreferenceUtil.setBoolean(getBaseContext(), CommonConstants.PRE_WIFI_SETTINGS_TIPS_OFF, isChecked));
        view.findViewById(R.id.btn_dialog_camera_live_settings_cancel).setOnClickListener(v -> mDialog.dismiss());
        view.findViewById(R.id.btn_dialog_camera_live_settings_submit).setOnClickListener(v -> {
            mDialog.dismiss();
            startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
        });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterICameraListener();
        deviceFacade.disconnect();
    }


    protected void updateLayout(boolean update) {

    }

    protected void updateServiceState(){

    }


    protected void setMultiChannelsStreamCtrl() {

    }

    public void accept(ConnectStatus connectStatus) {

    }


    private final Consumer<ConnectStatus> connectStatusConsumer = CameraBaseActivity.this::accept;

    private final Consumer<Instruction> instructionConsumer = instruction -> {
        if (instruction == null) {
            return;
        }
        final int type = instruction.getId();
        final byte[] data = instruction.getData();
        TGLog.i(TAG, "[instructionConsumer] type:" + type + " type1:" + AVIOCTRLDEFs.IOTYPE_USER_IPCAM_SETSTREAMCTRL_RESP);
        receiveIOCtrlData(type, data);
    };

    private void getServiceInfo() {
        if (mDevice == null) return;
        ServiceInfoHelper.getServiceInfo(mDevice.uuid, new ServiceInfoHelper.ServiceInfoListener<HashMap<String, DeviceServiceStatusBean>>() {
            @Override
            public void onSuccess(HashMap<String, DeviceServiceStatusBean> resp) {
                TGLog.i(TAG, "[query][onSuccess] resp = " + resp);
                if (resp != null){
                    DeviceServiceStatusBean deviceServiceStatusBean = resp.get(mDevice.uuid);
                    if (deviceServiceStatusBean != null){
                        mDevice.server_data = deviceServiceStatusBean.storage;
                        mDevice.sim_server_data = deviceServiceStatusBean.sim;
                        mDevice.car_server_data = deviceServiceStatusBean.car;
                        mDevice.ai_server_data = deviceServiceStatusBean.ai;
                        mDevice.foreignServiceHook = deviceServiceStatusBean.foreign_service_hook;
                        if (mDevice.server_bought == null){
                            mDevice.server_bought = new ServiceBought();
                        }
                        mDevice.server_bought.ai_server = deviceServiceStatusBean.bought.ai? 1 : 0;
                        mDevice.server_bought.car_server = deviceServiceStatusBean.bought.car? 1 : 0;
                        mDevice.server_bought.sim_server = deviceServiceStatusBean.bought.sim? 1 : 0;
                        mDevice.server_bought.server = deviceServiceStatusBean.bought.storage? 1 : 0;
                        updateServiceState();
                    }
                }
            }

            @Override
            public void onError(int errorCode, String errorInfo) {
                String msg = "errorCode = " + errorCode + " , errorInfo = " + errorInfo;
                TGLog.i(TAG, "[query][onResponseError] " + msg);
            }
        });
    }

    protected void showErrorTip() {
        if (connectView.getVisibility() == View.VISIBLE){
            TGToast.showToast(connectView.getText().toString());
        }else if (loadingView.getVisibility() == View.VISIBLE){
            TGToast.showToast(R.string.scan_qrcode_connecting);
        }
    }
}
